package com.netty.io.blockio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhangbq
 * @since 2020-12-04 15:22
 **/
public class BioSocketServer {
    public static class BioTaskChannel implements Runnable{
        private Socket socket;

        public BioTaskChannel(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            BufferedReader input = null;
            PrintWriter printWriter = null;

            //数据读取都是从Buffer里面读取，提高效率
            try {
                //读入流使用Buffer获取流
                input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                //写出，使用PrintWriter写出
                printWriter = new PrintWriter(this.socket.getOutputStream(),true);
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("BIO 通信发生异常， 异常信息 ： " + e.getMessage());
            }finally {
                if (null != input){
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != printWriter){
                    printWriter.close();
                }
                if (null != socket){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) throws IOException {
            //使用Java中的Socket服务
            ServerSocket serverSocket = new ServerSocket(666);
            //一直循环等待连接的到来
            while (true){
                new Thread(new BioTaskChannel(serverSocket.accept())).start();
            }
        }
    }
}
